package com.woniu.inlet.listen;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniu.adapter.SellRateAdapter;
import com.woniu.adapter.UserDetailAdapter;
import com.woniu.inlet.vo.ConfirmCurrentSellOrder;
import com.woniu.inlet.vo.FixedDayVo;
import com.woniu.inlet.vo.FixedMsgVo;
import com.woniu.outlet.client.OrderMessage;
import com.woniu.outlet.client.UpdateOrderStatus;
import com.woniu.outlet.mysql.ReceivedMsgOrderSellCurrentPayDao;
import com.woniu.outlet.mysql.po.ReceivedMsgOrderSellCurrentPayMySQL;
import com.woniu.outlet.mysql.po.SellRateMySQL;
import com.woniu.service.UserDetailService;
import com.woniu.service.bean.AddEarnings;
import com.woniu.service.bean.AddSellRecord;
import com.woniu.service.domain.UserDetail;
import com.woniu.util.AppUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 获取定期产品的卖出监听
 */
@Slf4j
@RabbitListener(queues = "order_sell_fixed_pay")
@Component
public class FixedSellOrderListener {

    @Autowired
    private ReceivedMsgOrderSellCurrentPayDao receivedMsgOrderSellCurrentPayDao;
    @Autowired
    private OrderMessage orderMessage;
    @Autowired
    private UserDetailAdapter userDetailAdapter;

    @Transactional // 抛出异常，事务回滚。
    @RabbitHandler
    public void handle(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        log.debug("开始监听队列");
        String[] strings = message.split("!");
        System.out.println(strings);
        if (strings.length < 2) {
            channel.basicReject(tag, false);
            throw new RuntimeException("接收到的消息内容格式错误");
        }

        // 消息的第一部分是：消息在【可靠消息服务】那边的消息表中的ID（唯一）。
        String messageIdString = strings[0];
        Integer messageId = Integer.parseInt(messageIdString);

        // 消息的第二部分是：订单模块发送过来的具体消息 。
        String substring = strings[1];

        try {
            // 1. 判断是否是重复消息：insert into 去重表
            receivedMsgOrderSellCurrentPayDao.insert(new ReceivedMsgOrderSellCurrentPayMySQL(null, messageId));
        } catch (RuntimeException e) {
            log.debug("该消息重复");
            // 2. 拒绝消息。要求 RabbitMQ 从队列中删除。
            channel.basicReject(tag, false);
            return;
        }

        try {
            log.debug("执行定期卖出业务");

            FixedDayVo fixedDayVo = JSON.parseObject(substring, FixedDayVo.class);
            //跟新用户余额
            //根据用户id查询用户
            UserDetail user = userDetailAdapter.getUserById(fixedDayVo.getUserId().intValue());
            UserDetail userDetail = new UserDetail();
            userDetail.setUserId(user.getUserId());
            userDetail.setRestAmount(user.getRestAmount().add(fixedDayVo.getIncome()).add(fixedDayVo.getTotalPrincipal()));
            userDetail.setTotalAmount(user.getTotalAmount().add(fixedDayVo.getIncome()));
            userDetailAdapter.updateInfo(userDetail);
            //给用户发送消息
            String inform = "您好，你已成功卖出【定期】产品：" + fixedDayVo.getName() + "-" + fixedDayVo.getUserId() + "-" + "y";
            orderMessage.sendMessage("pay.inform.user", "pay_inform_user", inform);
            //向卖出记录表添加数据
            AddSellRecord addSellRecord = new AddSellRecord();
            addSellRecord.setUserId(fixedDayVo.getUserId().intValue());
            addSellRecord.setDealTime(AppUtils.getNowTimeStr());
            addSellRecord.setDealPrice(fixedDayVo.getIncome().add(fixedDayVo.getTotalPrincipal()));
            addSellRecord.setUserIncome(fixedDayVo.getIncome());
            //定期卖出不收手续费
            addSellRecord.setDealCharge(new BigDecimal(0));
            addSellRecord.setProductType(fixedDayVo.getProductType());
            addSellRecord.execute();
            // 确认接收，并处理该消息：
            channel.basicAck(tag, false);
            // 发起 HTTP 请求: http://可靠消息服务/message/{}/received"
            orderMessage.receivedMessage(messageId);
        } catch (RuntimeException e) {
            // 执行本地业务出错，拒绝消息，要求 RabbitMQ 从队列中删除。
            // 等待发送者的定时器下次再发送一次。
            channel.basicReject(tag, false);
            throw new NullPointerException();
        }
    }

}
